package cn.dslcode.security.config.oauth2;

import cn.dslcode.security.config.CustomSecurityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	
	@Autowired
    private AuthenticationManager authenticationManager;
	@Autowired
	private UserDetailsService userDetailsService;
    @Autowired
    private OAuth2BeanConfiguration oauth2Beans;
    @Autowired
    private CustomSecurityConstant securityConstant;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(oauth2Beans.clientDetailsService());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    	security
    		.accessDeniedHandler(oauth2Beans.oauth2AccessDeniedHandler())
        	.authenticationEntryPoint(oauth2Beans.oauth2AuthenticationEntryPoint())
            .checkTokenAccess("isAuthenticated()") ///oauth/check_token 权限
        	.allowFormAuthenticationForClients()//允许表单认证
            .addTokenEndpointAuthenticationFilter(new CustomCaptchaVerifyFilter(
                authenticationManager,
                oauth2Beans.oAuth2RequestFactory(),
                securityConstant.getParameterName().getCaptchaCode()
            ))
        ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .authenticationManager(authenticationManager)
            .userDetailsService(userDetailsService)
            .userApprovalHandler(oauth2Beans.userApprovalHandler())
            .approvalStore(oauth2Beans.approvalStore())
            .authorizationCodeServices(oauth2Beans.authorizationCodeServices())
            .tokenStore(oauth2Beans.tokenStore())
        ;
    }

}